package com.szgr.baoyin.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.activity.CartActivity;
import com.szgr.baoyin.model.Product;
import com.szgr.baoyin.myview.indexbar.IndexableListView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yang on 15/10/16.
 */
public class CartListAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener, View.OnClickListener{
    private Context mContext;
    private List<Product> data;
    private CartInterface cif;

    public CartListAdapter(Context context, List<Product> data,CartActivity ca) {
        mContext = context;
        this.data = data;
        cif = (CartInterface) ca;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_cart_list_view, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }

        if(data != null && data.size() > 0) {
            holder = (ViewHolder) convertView.getTag();
            final Product product = data.get(position);
            holder.cb_check.setTag(position);
            holder.cb_check.setChecked(product.isChecked());
            MyTool.showPicture(mContext, holder.img_image, product.getImgUrl());
            holder.tv_name.setText(product.getName());
            String newPrice = product.getNewPrice();
            if (newPrice != null) {
                holder.tv_newPrice.setText("¥" + newPrice);
            }
            String oldPrice = product.getOldPrice();
            if (oldPrice != null) {
                holder.tv_oldPrice.setText("¥" + oldPrice);
            }
            holder.et_count.setText(product.getCount());

            holder.cb_check.setOnCheckedChangeListener(this);
            holder.tv_minus.setTag(position);
            holder.tv_minus.setOnClickListener(this);
            holder.tv_add.setTag(position);
            holder.tv_add.setOnClickListener(this);
            holder.et_count.setTag(position);
            holder.et_count.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus && data.size() > 0) {
                        int tag = (int) v.getTag();
                        String temp = ((EditText) v).getText().toString();
                        if(temp == null || "".equals(temp)){
                            data.get(tag).setCount("1");
                            editCart("1", data.get(tag));
                        }else {
                            data.get(tag).setCount(temp);
                            editCart(temp, data.get(tag));
                        }
                        calculatePrice();
                    }
                }
            });
            holder.img_delete.setTag(position);
            holder.img_delete.setOnClickListener(this);
        }
        return convertView;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        data.get((int)buttonView.getTag()).setIsChecked(isChecked);
        notifyDataSetChanged();
        calculatePrice();
    }

    private boolean calculatePrice() {
        double money = 0;
        int checkCount = 0;
        boolean isAllCheck = false;
        for (Product p : data) {
            if (p.isChecked()) {
                money += Double.parseDouble(p.getNewPrice()) * Double.parseDouble(p.getCount());
                checkCount++;
            }
        }
        if (checkCount == data.size()) {
            isAllCheck = true;
        }
        cif.cartBack(money, isAllCheck);
        return isAllCheck;
    }

    @Override
    public void onClick(View v) {
        int tag = (int) v.getTag();
        Product product = data.get(tag);
        int count = Integer.parseInt(product.getCount());
        switch (v.getId()) {
            case R.id.cart_minus:
                if(count >= 2){
                    editCart(String.valueOf(--count), product);
                }
                break;
            case R.id.cart_add:
                editCart(String.valueOf(++count), product);
                break;
            case R.id.cart_delete:
//                deleteCart(product);
                cif.cartBack(tag);
                break;
        }
    }

    /**
     * 修改购物车商品数目
     * @param count
     */
    private void editCart(final String count,final Product p) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_EDIT_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---edit--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            if(datas.has("quantity")){
                                String quantity = datas.getString("quantity");
                                p.setCount(quantity);
                                notifyDataSetChanged();
                                calculatePrice();
                            }
                        } catch (JSONException e) {
                            ToastUtils.showToast("修改商品数目失败，请检查网络");
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("cart_id",p.getCart_id());
                map.put("quantity",count);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    Product p = (Product) msg.obj;
                    data.remove(p);
                    notifyDataSetChanged();
                    calculatePrice();
                    break;
            }
        }
    };

    /**
     * 删除条目
     */
    /**
     * 加入购物车
     */
    private void deleteCart(final Product p) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_DELETE_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                Object datas = jsonObject.get("datas");
                                if(datas instanceof String){
                                    String str = (String) datas;
                                    if("1".equals(str)){
                                        //删除成功
                                        mHandler.obtainMessage(Constant.REQUEST_SUCCESS,p).sendToTarget();
                                    }
                                }else if(datas instanceof JSONObject){
                                    String error = ((JSONObject) datas).getString("error");
                                    ToastUtils.showToast(error);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("cart_id",p.getCart_id());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }



    public void setData(List<Product> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    private class ViewHolder {
        CheckBox cb_check;
        ImageView img_image;
        TextView tv_name;
        TextView tv_newPrice;
        TextView tv_oldPrice;
        TextView tv_minus;
        TextView tv_add;
        EditText et_count;
        ImageView img_delete;

        public ViewHolder(View view) {
            cb_check = (CheckBox) view.findViewById(R.id.cart_check);
            img_image = (ImageView) view.findViewById(R.id.cart_image);
            tv_name = (TextView) view.findViewById(R.id.cart_name);
            tv_newPrice = (TextView) view.findViewById(R.id.cart_new_price);
            tv_oldPrice = (TextView) view.findViewById(R.id.cart_old_price);
            tv_minus = (TextView) view.findViewById(R.id.cart_minus);
            tv_add = (TextView) view.findViewById(R.id.cart_add);
            et_count = (EditText) view.findViewById(R.id.cart_count);
            img_delete = (ImageView) view.findViewById(R.id.cart_delete);
        }
    }

    public interface CartInterface {
        void cartBack(double money, boolean isAllCheck);
        void cartBack(int position);
    }

}
